const path = require('path');
const chalk = require('chalk');
const config = require('./src/variableConfig');
let MY_ENV = 'dev';

let params = [];
// 获取命令行变量
if (process.env && process.env.npm_config_argv) {
  const NPM_CONFIG_ARGV = JSON.parse(process.env.npm_config_argv);
  const original = NPM_CONFIG_ARGV.original.slice(1);
  const arr = original[0].split(':');
  if (arr[2]) {
    params.push(arr[2]);
  }
  if (arr[3]) {
    params.push(arr[3]);
  }
  MY_ENV = arr[1] || 'dev';
}

console.log(chalk.yellow(`  当前环境：${MY_ENV}\n`));
console.log(
  chalk.yellow(
    `  当前域名：${require('./src/variableConfig')(MY_ENV).baseHost}\n`
  )
);
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: config(MY_ENV).baseHost, // API服务器的地址
        ws: true, // 代理websockets
        changeOrigin: true, // 虚拟的站点需要更管origin
        pathRewrite: {
          // 重写路径 比如'/api/aaa/ccc'重写为'/aaa/ccc'
          // '^/api': .'
        }
      }
    }
  },
  publicPath: '/',
  chainWebpack: config => {
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal'];
    types.forEach(type =>
      addStyleResource(config.module.rule('stylus').oneOf(type))
    );
    // 路由懒加载生效配置
    config.plugins.delete('prefetch');

    // 设置全局变量 MY_ENV
    config
      .plugin('define')
      .tap(args => {
        args[0]['process.env.MY_ENV'] = JSON.stringify(MY_ENV);
        params.forEach(item => {
          args[0][`process.env.${item.toUpperCase()}`] = JSON.stringify(item);
        });
        console.log('args :', args);
        return args;
      })
      .end();
  }
};

function addStyleResource(rule) {
  rule
    .use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [path.resolve(__dirname, './src/assets/styles/common.styl')]
    });
}
